/**
 * 主应用文件
 *
 * @author bian
 * @createDate 2016.10.1
 */
"use strict";
process.env.UV_THREADPOOL_SIZE=100;

process.env.UV_THREADPOOL_SIZE = 100;
// load native modules
var http = require("http");
var path = require("path");
var util = require("util");

// load 3rd modules
var koa = require("koa");
var router = require("koa-router")();
var koaBodyParser = require("koa-bodyparser")

var serve = require("koa-static");
var colors = require("colors");
var open = require("open");

// load local modules
var pkg = require("../package.json");
var apiProxy = require("./instances/proxy").apiProxy;
var env = process.argv[2] || process.env.NODE_ENV;
var debug = "production" !== env;
var viewDir = debug ? "src" : "assets";
var staticDir = path.resolve(__dirname, "../" + "assets");
var publicDir = path.resolve(__dirname,"./" + "public");
// load routes
var routes = require("./routes/index.js");

// init framework
var app = koa();

colors.setTheme({
    silly: "rainbow",
    input: "grey",
    verbose: "cyan",
    prompt: "grey",
    info: "green",
    data: "grey",
    help: "cyan",
    warn: "yellow",
    debug: "blue",
    error: "red"
});

// basic settings
app.keys = [pkg.name, pkg.description];
app.proxy = true;

// global events listen
app.on("error", (err, ctx) => {
    err.url = err.url || ctx.request.url;
    if(err.errno === "EPIPE" || err.errno === "ECONNRESET"){
        return;
    }
    console.error(err, ctx);
});

// handle favicon.png
app.use(function*(next) {
    if (this.url.match(/favicon\.png$/)) this.body = "";
    yield next;
});

if(debug) {
    var webpackDevMiddleware = require("koa-webpack-dev-middleware");
    var webpack = require("webpack");
    var webpackConf = require("../webpack-dev.config");
    var compiler = webpack(webpackConf);

    // 为使用Koa做服务器配置koa-webpack-dev-middleware
    app.use(webpackDevMiddleware(compiler, webpackConf.devServer));

    // app.use(require("koa-webpack-hot-middleware")(compiler));
    // // 为实现HMR配置webpack-hot-middleware
    var hotMiddleware = require("webpack-hot-middleware")(compiler);
    // Koa对webpack-hot-middleware做适配
    app.use(function* (next) {
        yield hotMiddleware.bind(null, this.req, this.res);
        yield next;
    });
}

// handle static files
app.use(serve(staticDir, {
    maxage: 0
}));

// handle public files
app.use(serve(publicDir, {
    maxage: 0
}));

// logger
app.use(function*(next) {
    console.log(this.method.info, this.url)
    yield next
});

app.use(koaBodyParser())

require('koa-validate')(app)

// use routes
app.use(routes());

/**
 * proxy ajax request
 */
app.use(apiProxy("education",{
    // host: "210.30.100.4",
    host : "localhost",
    // port : 8000
    port : 8765
}));

app = http.createServer(app.callback());

// if(debug){
    app.listen(pkg.localServer.port);
// }

// app.listen(pkg.localServer.port, "127.0.0.1", () => {
//     var url = util.format("http://%s:%d", "localhost", pkg.localServer.port);
//
//     console.log("Listening at %s", url);
//
//     // open(url);
// });

module.exports = app;